from typing import Dict, List
from bs4 import BeautifulSoup
import os
import logging

class HTMLConverter:
    """HTML转换器核心类"""
    
    def __init__(self, template_dir: str = 'templates'):
        self.template_dir = template_dir
        self.template_cache: Dict[str, BeautifulSoup] = {}
        
    def _load_template(self, template_name: str) -> BeautifulSoup:
        """加载模板文件（带缓存和失效检查）
        
        Args:
            template_name: 模板文件名
            
        Returns:
            BeautifulSoup: 解析后的模板对象
            
        Raises:
            FileNotFoundError: 当模板文件不存在时
        """
        if template_name not in self.template_cache:
            template_path = os.path.join(self.template_dir, template_name)
            try:
                with open(template_path, 'r', encoding='utf-8') as f:
                    self.template_cache[template_name] = BeautifulSoup(f.read(), 'html.parser')
            except FileNotFoundError as e:
                logging.error(f"模板文件未找到: {template_path}")
                raise
        return self.template_cache[template_name]
        
    def convert_article(self, article: Dict[str, str], template: str) -> str:
        """转换单篇文章"""
        soup = self._load_template(template)
        
        # 替换模板变量
        if '{{title}}' in str(soup):
            title_tag = soup.find(text='{{title}}')
            if title_tag:
                title_tag.replace_with(article.get('title', ''))
        
        if '{{content}}' in str(soup):
            content_tag = soup.find(text='{{content}}')
            if content_tag:
                content_tag.replace_with(article.get('content', ''))
        
        if '{{link}}' in str(soup):
            link_tag = soup.find(text='{{link}}')
            if link_tag:
                link_tag.replace_with(article.get('link', ''))
        
        return str(soup)

    def batch_convert(self, articles: List[Dict[str, str]], template: str) -> str:
        """批量转换文章"""
        results = []
        for article in articles:
            results.append(self.convert_article(article, template))
        return '\n'.join(results)